package sd.rmi.auction.server;

import java.rmi.RemoteException;
import java.rmi.server.UnicastRemoteObject;
import java.util.Collection;
import java.util.Iterator;
import java.util.Vector;

import sd.rmi.auction.interfaces.IAuction;
import sd.rmi.auction.interfaces.INotifiable;

/**
 * 
 * @author v
 *
 */
public class Auctioneer extends UnicastRemoteObject implements IAuction {

    private int bid = -1;
    private String product;
    private Collection<INotifiable> clients = null;

    /**
     *
     * @param name
     * @param price
     * @throws RemoteException
     */
    protected Auctioneer(String name, int price) throws RemoteException {
        super();
        this.product = name;
        this.bid = price;
        clients = new Vector<INotifiable>();
    }
    /**
     *
     */
    private static final long serialVersionUID = 1L;

    @Override
    public int getCurrentBid() throws RemoteException {
        return bid;
    }

    @Override
    public String getProduct() throws RemoteException {
        return product;
    }

    @Override
    public void setBid(int bid) throws RemoteException {
        //synchronized (this) {
            if (this.bid < bid) {
                System.out.println("Offerta accettata");
                this.bid = bid;
                //notifico che l'offerta � stata accetta e il prezzo attuale
                INotifiable tmp;
                synchronized (clients) {
                	for (Iterator<INotifiable> it = clients.iterator(); it.hasNext();)
                    {
                        tmp = it.next();
                        tmp.notify(bid);
                    }
				}
                

                /* //this is not thread-safe
                for (INotifiable client: clients)
                client.notify(bid);
                 */
            } else {
                System.out.println("Offerta bassa non accettata");
            }
            this.bid = this.bid < bid ? bid : this.bid;
        //}
    }

    @Override
    public void registerForNotification(INotifiable n) throws RemoteException {
        System.out.print("Il client " + n.toString() + " si sta registrando");
        clients.add(n);
    }
}
